<?php
/**
 * Created by PhpStorm.
 * User: dong
 * Date: 2018/3/26
 * Time: 19:32
 */
namespace App\Services\ThirdPayments\Recharge;

use App\Exceptions\RechargeGatewayException;
use App\Lib\Code;
use App\Lib\PaymentMap;
use App\Lib\ThirdPartyMap;
use App\Models\RechargeOrder;
use App\Services\ThirdPayments\Contracts\Actions\HrefRedirectAction;
use App\Services\ThirdPayments\Contracts\RechargeBaseAbstract;
use App\Services\ThirdPayments\Contracts\WAPable;

class QIANYINGPayment extends RechargeBaseAbstract implements WAPable
{
    protected $gw_pay = 'http://ican.8tec.cn/pay.php';

    public function callback(array $data)
    {
        // TODO: Implement callback() method.
        if ($this->veryCallbackSign($data)) {
            $status = $data['status'];
            if ($status == "1" || $status == "5" || $status == "6") {
                return true;
            }
        }
        return false;
    }

    public function veryCallbackSign(array $data)
    {
        // TODO: Implement veryCallbackSign() method.
        $orderid = $data["oid"];        //订单号
        $status = $data["status"];      //处理结果：【1：支付完成；2：超时未支付，订单失效；4：处理失败，详情请查看msg参数；5：订单正常完成（下发成功）；6：补单；7：重启网关导致订单失效；8退款】
        $money = $data["m1"];            //实际充值金额
        $sign = $data["sign"];          //签名，用于校验数据完整性
        $orderidMy = $data["oidMy"];    //千应录入时产生流水号，建议保存以供查单使用
        $orderidPay = $data["oidPay"];  //收款方的订单号（例如支付宝交易号）;
        $completiontime = $data["time"];//千应处理时间
        $attach = $data["token"];       //上行附加信息
        $param="oid=".$orderid."&status=".$status."&m=".$money. $this->getMchKey();  //拼接$param

        $paramMd5=md5($param);          //md后加密之后的$param

        if(strcasecmp($sign,$paramMd5)==0){
            if($status == "1" || $status == "5" || $status == "6"){

                return true;
            }
        }
        return false;
    }

    public function getOrderNoFromCallback(array $data)
    {
        // TODO: Implement getOrderNoFromCallback() method.
        return $data['oid'];
    }

    public function getOrderAmtFromCallback(array $data)
    {
        // TODO: Implement getOrderAmtFromCallback() method.
        return $data['mInt'];
    }

    /**
     * @return mixed
     */
    public function getIdentify(): string
    {
        // TODO: Implement getIdentify() method.
        return ThirdPartyMap::QIANYING;
    }

    /**
     *  needs child to achieve
     */
    public function initPaymentMap(): array
    {
        // TODO: Implement initPaymentMap() method.
        return [
            PaymentMap::ALI => '101',
            PaymentMap::WX => '102',
            PaymentMap::ALI_WAP => '101',
            PaymentMap::WX_WAP  => '102'
        ];
    }

    public function query(RechargeOrder $rechargeOrder)
    {
        // TODO: Implement query() method.
    }

    public function bankHref(RechargeOrder $rechargeOrder)
    {
        // TODO: Implement bankHref() method.
    }

    public function scanCode(RechargeOrder $rechargeOrder)
    {
        // TODO: Implement scanCode() method.
        $this->initParameters($rechargeOrder);
        return $this->getGwPay() .'?'. http_build_query($this->getParameters());
    }

    public function paySign(): string
    {
        // TODO: Implement paySign() method.
        $signStr = "";
        $signStr .= "uid=" . $this->getParameter('uid') . '&';
        $signStr .= "type=" . $this->getParameter('type') . '&';
        $signStr .= "m=" . $this->getParameter('m') . '&';
        $signStr .= "orderid=" . $this->getParameter('orderid') . '&';
        $signStr .= "callbackurl=" . $this->getParameter('callbackurl') ;
        $signStr .= $this->getMchKey();
        return md5($signStr);
    }

    public function querySign(): string
    {
        // TODO: Implement querySign() method.
    }

    public function showSuccess(): string
    {
        // TODO: Implement showSuccess() method.
        return 'ok';
    }

    public function initParameters(RechargeOrder $rechargeOrder)
    {
        if (bccomp($rechargeOrder->order_amt, (int)$rechargeOrder->order_amt, 2) != 0) {
            throw new RechargeGatewayException('此接口必须接收整数金额', Code::RECHARGE_THIRD_LOG);
        }
        $mchData = $rechargeOrder->order_data;
        // TODO: Implement initParameters() method.
        $this->setParameter('uid', $this->getMchId());
        $this->setParameter('type', $this->getPaymentMap($mchData['recharge_type']));
        $this->setParameter('m', (int)$rechargeOrder->order_amt);
        $this->setParameter('orderid', $rechargeOrder->plat_no);
        $this->setParameter('callbackurl', $this->getCallbackUrl());
        $this->setParameter('gotrue', $this->getReturnUrl() . '?mInt=' .$this->getParameter('m') . '&oid=' . $this->getParameter('orderid'));
        $this->setParameter('gofalse', route('gateway.recharge.expired'));
        $this->setParameter('sign', $this->paySign());
    }

    public function wapReq(RechargeOrder $rechargeOrder)
    {
        // TODO: Implement wapReq() method.
        $this->initParameters($rechargeOrder);
        return new HrefRedirectAction($this->getGwPay() .'?'. http_build_query($this->getParameters()));
    }
}
